package com.yc.txx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.txx.entity.User;
import com.yc.txx.mapper.UserMapper;
import com.yc.txx.service.BizException;
import com.yc.txx.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.txx.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 天下行租车-用户表-4 服务实现类
 * </p>
 *
 * @author xl
 * @since 2024-05-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User login(User user) throws BizException {
        Utils.check(Utils.isEmpty(user.getEname()),"请输入用户名");
        Utils.check(Utils.isEmpty(user.getPassword()),"请输入密码");
        // 条件构建器
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        // ename = ?
        lqw.eq(User::getEname, user.getEname());
        // ename = ? and password = ?
        lqw.eq(User::getPassword, user.getPassword());
        List<User> list = this.list(lqw);
        Utils.check(list.isEmpty(),"用户名或密码错误!");
        Utils.check(list.size()>1,"系统错误,请联系管理员!");
        return list.get(0);
    }

    @Override
    public void register(User user) throws BizException {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getEname,user.getEname());
        //Utils.check(count()>0,"该账号语句注册");
        if(count(lqw)>0){
            throw new BizException("该账号已经注册","ename");
        }

        lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getEamil,user.getEamil());
        //Utils.check(count()>0,"该邮箱语句注册");
        if(count(lqw)>0){
            throw new BizException("该邮箱已经注册","eamil");
        }

        this.save(user);
    }


    @Override
    public void updateUserInfo(User user) throws BizException {
        Utils.check(user.getCname().isEmpty(),"请输入你的昵称","cname");
        Utils.check(user.getEamil().isEmpty(),"请输入你的邮箱","eamil");
        this.updateById(user);
    }

    @Override
    public void upPwd(User user, String newPwd) throws BizException {
        //条件构建器
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getId , user.getId());
        lqw.eq(User::getPassword , user.getPassword());

        Utils.check(count(lqw)==0,"你的原密码输入有误，请重新输入","password");
        Utils.check(newPwd.length()<6 || newPwd.length() > 16,"密码长度要求6-16位");

        user.setPassword(newPwd);
        userMapper.updateById(user);
    }
}
